import pygame
import sys
from typing import Tuple

# 常量定义
COLOR_LOCKER_BG = (30, 30, 50)  # 深蓝色背景
COLOR_LOCKER_FRAME = (70, 70, 120)  # 锁框颜色
COLOR_LOCKER_BUTTON = (100, 100, 150)  # 按钮颜色
COLOR_HIGHLIGHT = (180, 180, 220)  # 高亮颜色
COLOR_TEXT = (220, 220, 250)  # 文字颜色
COLOR_CORRECT = (100, 200, 100)  # 正确输入的颜色
COLOR_WRONG = (220, 100, 100)  # 错误输入的颜色
COLOR_DIGIT_BG = (40, 40, 70)  # 数字背景色
COLOR_DIGIT_FRAME = (90, 90, 140)  # 数字边框色


class LockVisualizer:
    """
    机关锁解密界面类 - 三位数字轮盘版
    """
    def __init__(self):
        """
        直接作为工具
        """
        pygame.init()
        self.width = 600
        self.height = 400
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption('解迷环节')

        self.active = False
        self.correct_password = "789"  # 正确的密码
        self.hint_text = "三个连续的数加起来等于24"  # 谜题提示
        self.message = ""
        self.message_timer = 0

        # 数字设置 (0-9 循环)
        self.digits = [0, 0, 0]  # 初始为000
        self.selected_digit_index = 0  # 当前选中的数字位索引

        # 创建字体
        self.title_font = self.get_font(40)
        self.text_font = self.get_font(28)
        self.digit_font = self.get_font(56)
        self.button_font = self.get_font(20)

        # 数字框区域
        self.digit_rects = []
        self.create_digit_areas()

    # 新增方法：获取支持中文的字体
    def get_font(self, size):
        """获取支持中文的字体，带有多重回退机制"""
        # 尝试加载系统字体
        # Windows 系统常用中文字体
        for font_name in ["Microsoft YaHei", "SimHei", "KaiTi", "SimSun"]:
            try:
                return pygame.font.SysFont(font_name, size)
            except:
                continue

        # macOS 系统常用中文字体
        for font_name in ["PingFang SC", "Hiragino Sans GB", "STHeiti"]:
            try:
                return pygame.font.SysFont(font_name, size)
            except:
                continue

        # Linux 系统常用中文字体
        for font_name in ["WenQuanYi Micro Hei", "Noto Sans CJK SC"]:
            try:
                return pygame.font.SysFont(font_name, size)
            except:
                continue

        # 最终回退方案
        try:
            # 尝试加载内置字体
            return pygame.font.Font(None, size)
        except:
            # 终极回退方案
            return pygame.font.SysFont("Arial", size)

    def create_digit_areas(self):
        """创建数字框区域"""
        digit_size = 100
        spacing = 30
        start_x = self.width // 2 - (3 * digit_size + 2 * spacing) // 2
        start_y = self.height // 2 - digit_size // 2 - 40

        for i in range(3):
            rect = pygame.Rect(
                start_x + i * (digit_size + spacing),
                start_y,
                digit_size,
                digit_size
            )
            self.digit_rects.append(rect)

    def activate(self):
        """激活解密界面"""
        self.active = True
        self.digits = [0, 0, 0]  # 重置为000
        self.selected_digit_index = 0  # 默认选中第一位
        self.message = ""

    def deactivate(self):
        """关闭解密界面"""
        self.active = False

    def handle_event(self, event: pygame.event.Event):
        """处理事件"""
        if not self.active:
            return False

        if event.type == pygame.KEYDOWN:
            # 左右键切换选中的数字位
            if event.key == pygame.K_LEFT:
                self.selected_digit_index = (self.selected_digit_index - 1) % 3
                return True
            elif event.key == pygame.K_RIGHT:
                self.selected_digit_index = (self.selected_digit_index + 1) % 3
                return True

            # 上下键调整当前数字位的值
            elif event.key == pygame.K_UP:
                self.digits[self.selected_digit_index] = (self.digits[self.selected_digit_index] + 1) % 10
                return True
            elif event.key == pygame.K_DOWN:
                self.digits[self.selected_digit_index] = (self.digits[self.selected_digit_index] - 1) % 10
                # 处理负数情况
                if self.digits[self.selected_digit_index] < 0:
                    self.digits[self.selected_digit_index] = 9
                return True

            # 回车键提交
            elif event.key == pygame.K_RETURN:
                # 将数字列表转换为字符串
                password = ''.join(str(d) for d in self.digits)
                if password == self.correct_password:
                    self.message = "解锁成功!"
                    pygame.time.delay(1000)  # 短暂延迟显示成功消息
                    return "SUCCESS"
                else:
                    self.message = "密码错误，请重试"
                return True

        return False

    def draw(self):
        """绘制解密界面"""
        if not self.active:
            return

        # # 绘制半透明背景
        # overlay = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        # overlay.fill((0, 0, 0, 180))  # 黑色半透明
        # self.screen.blit(overlay, (0, 0))

        # 绘制主框
        frame_rect = pygame.Rect(0, 0, self.width, self.height)
        pygame.draw.rect(self.screen, COLOR_LOCKER_BG, frame_rect)
        pygame.draw.rect(self.screen, COLOR_LOCKER_FRAME, frame_rect, 4)

        # 标题
        title = self.title_font.render("机关锁", True, COLOR_TEXT)
        self.screen.blit(title, (self.width // 2 - title.get_width() // 2, frame_rect.top + 20))

        # 直接显示提示文本
        hint = self.text_font.render(f"提示: {self.hint_text}", True, COLOR_TEXT)
        self.screen.blit(hint, (self.width // 2 - hint.get_width() // 2, frame_rect.top + 70))

        # 绘制数字框
        for i, rect in enumerate(self.digit_rects):
            # 绘制数字框背景
            color = COLOR_HIGHLIGHT if i == self.selected_digit_index else COLOR_DIGIT_BG
            pygame.draw.rect(self.screen, color, rect)
            pygame.draw.rect(self.screen, COLOR_DIGIT_FRAME, rect, 3)

            # 绘制数字
            digit_text = self.digit_font.render(str(self.digits[i]), True, COLOR_TEXT)
            self.screen.blit(digit_text, (rect.centerx - digit_text.get_width() // 2,
                                          rect.centery - digit_text.get_height() // 2))

            # 绘制数字位指示器
            indicator_y = rect.bottom + 10
            if i == self.selected_digit_index:
                # 绘制三角形指示器
                points = [
                    (rect.centerx, indicator_y),
                    (rect.centerx - 10, indicator_y - 15),
                    (rect.centerx + 10, indicator_y - 15)
                ]
                pygame.draw.polygon(self.screen, COLOR_HIGHLIGHT, points)

        # 绘制操作说明
        instructions = [
            "操作说明:",
            "← → : 切换数字位",
            "↑ ↓ : 调整数字大小",
            "回车 : 提交密码"
        ]

        for j, text in enumerate(instructions):
            instr = self.text_font.render(text, True, COLOR_TEXT)
            self.screen.blit(instr, (self.width // 2 - instr.get_width() // 2,
                                     frame_rect.top + 240 + j * 35))

        # 消息显示
        if self.message:
            color = COLOR_CORRECT if "成功" in self.message else COLOR_WRONG
            msg_surface = self.text_font.render(self.message, True, color)
            self.screen.blit(msg_surface, (self.width // 2 - msg_surface.get_width() // 2,
                                           frame_rect.bottom - 40))